package com.ziyun.erp.modules.goods.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utility.New;
import com.ziyun.erp.common.utils.GoodsMonitorUtils;
import com.ziyun.erp.modules.goods.dao.GoodsAttributeDao;
import com.ziyun.erp.modules.goods.dao.GoodsOptionDao;
import com.ziyun.erp.modules.goods.entity.GoodsAttributeEntity;
import com.ziyun.erp.modules.goods.entity.GoodsOptionEntity;
import com.ziyun.erp.modules.goods.entity.GoodsTemplateEntity;
import com.ziyun.erp.modules.goods.service.GoodsAttributeService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goodsMonitor.entity.GoodsMonitorEntity;
import com.ziyun.erp.modules.goodsMonitor.service.GoodsMonitorService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("goodsAttributeService")
public class GoodsAttributeServiceImpl extends ServiceImpl<GoodsAttributeDao, GoodsAttributeEntity> implements GoodsAttributeService {

    @Autowired
    private GoodsAttributeDao goodsAttributeDao;

    @Autowired
    private GoodsOptionDao goodsOptionDao;

    @Autowired
    private GoodsTemplateService goodsTemplateService;

    @Autowired
    private GoodsMonitorService goodsMonitorService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer attributeId = StringUtil.getRequestParamInteger(params.get("attributeId"));
        String attributeName = StringUtil.getRequestParamString(params.get("attributeName"));
        Page<GoodsAttributeEntity> page = this.selectPage(
                new Query<GoodsAttributeEntity>(params).getPage(),
                new EntityWrapper<GoodsAttributeEntity>()
                .eq("disabled",0)
                .eq(attributeId != null,"attribute_id",attributeId)
                .eq("date_flag",0)
                .like(StringUtils.isNotBlank(attributeName),"attribute_name",attributeName)
        );
        return new PageUtils(page);
    }

    public Page<GoodsAttributeEntity> queryNewPage(Page<GoodsAttributeEntity> page,Map<String, Object> params){
        page.setRecords(this.baseMapper.queryNewPage(page,params));
        return page;
    }

    /**
     * 根据规格值获得规格名
     * @param optionIds
     * @return
     */
    @Override
    public String getAttributeNamesByOptionIds(String optionIds) {
        String attributeNames = goodsAttributeDao.getAttributeNamesByOptionIds(optionIds);
        return attributeNames;
    }

    /**
     * 根据工艺配价值获得工艺名
     * @param craftOptionIds
     * @return
     */
    @Override
    public String getCraftNamesByCraftOptionIds(String craftOptionIds) {
        String craftNames = goodsAttributeDao.getCraftNamesByCraftOptionIds(craftOptionIds);
        return craftNames;
    }

    /**
     * 根据模板id获得其规格值(排除工艺属性)
     * @param templateId
     * @return
     */
    @Override
    public R getAttributesByTemplateId(Integer templateId,Long sellerId) {
        //原方法一:
        /*List<GoodsAttributeEntity> attributes = getAttributeType(templateId, "normal");
        HashMap<String, Object> map = new HashMap<>();
        for(int i=0;i<attributes.size();i++){
            map.clear();
            map.put("disabled",0);
            map.put("attribute_id",attributes.get(i).getAttributeId());
            List<GoodsOptionEntity> goodsOptionEntities = goodsOptionDao.selectByMap(map);
            attributes.get(i).setGoodsOptionList(goodsOptionEntities);
        }
//        return attributes;
        List<GoodsAttributeEntity> craftAttributes = getCraftAttributesByTemplateId(templateId);*/
        //修改过后的方法二:
        //根据模板id取到optionJson
        GoodsTemplateEntity goodsTemplateEntity = goodsTemplateService.selectById(templateId);
        String optionJson = goodsTemplateEntity.getOptionJson();
        if(StringUtils.isBlank(optionJson)){
            return R.error("错误的模板格式");
        }
        JSONArray jsonArray = JSONArray.fromObject(optionJson);

        //根据attributeType区分规格和工艺
        List<GoodsAttributeEntity> attributes = new ArrayList<>();
        List<GoodsAttributeEntity> craftAttributes = new ArrayList<>();
        for(int i = 0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long attributeId = Long.valueOf(jsonObject.get("attributeId").toString());
            JSONArray optionId = jsonObject.getJSONArray("optionId");
            GoodsAttributeEntity goodsAttribute = goodsAttributeDao.selectById(attributeId);
            List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.selectByOptionIds(optionId.join(","));
            if(goodsOptionEntityList.size() != 0){
                goodsAttribute.setGoodsOptionList(goodsOptionEntityList);
                if("normal".equals(goodsAttribute.getAttributeType())){
                    attributes.add(goodsAttribute);
                }else if("craft".equals(goodsAttribute.getAttributeType())){
                    craftAttributes.add(goodsAttribute);
                }
            }
        }
        //------------------------------------------------
        //找到当前登录人sellerId私有的选项id
        List<GoodsOptionEntity> privateOptionList = goodsAttributeDao.getPrivateOptionByAttributeIds(goodsTemplateEntity.getAttributeIds(),sellerId);
        if(privateOptionList != null && privateOptionList.size() > 0){
            if(attributes != null && attributes.size() > 0){
                for(int i = 0 ;i<attributes.size();i++){
                    for(int j = 0;j<privateOptionList.size();j++){
                        if(attributes.get(i).getAttributeId().longValue() == privateOptionList.get(j).getAttributeId().longValue()){
                            attributes.get(i).getGoodsOptionList().add(privateOptionList.get(j));
                        }
                    }
                }
            }else{
                throw new RRException("模板下规格信息异常");
            }
        }
        return R.ok().put("attributeList",attributes).put("craftAttributeList",craftAttributes);
    }

    /**
     * 根据模板id获得其工艺值(排除规格属性)
     * @param templateId
     * @return
     */
    @Override
    public List<GoodsAttributeEntity> getCraftAttributesByTemplateId(Integer templateId) {
        List<GoodsAttributeEntity> attributes = getAttributeType(templateId, "craft");
        HashMap<String, Object> map = new HashMap<>();
        //优化:没有工艺就不查
        for(int i=0;i<attributes.size();i++){
            map.clear();
            map.put("disabled",0);
            map.put("attribute_id",attributes.get(i).getAttributeId());
            List<GoodsOptionEntity> goodsOptionEntities = goodsOptionDao.selectByMap(map);
            attributes.get(i).setGoodsOptionList(goodsOptionEntities);
        }
        return attributes;
    }

    /**
     * 更新规格拿到返回规格id
     * @param goodsAttribute
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveAttriute(GoodsAttributeEntity goodsAttribute) {
        goodsAttributeDao.saveAttribute(goodsAttribute);
        Long attributeId = goodsAttribute.getAttributeId();
        List<GoodsOptionEntity> goodsOptionList = goodsAttribute.getGoodsOptionList();
        for (int i = 0;i<goodsOptionList.size();i++){
            goodsOptionList.get(i).setCreateName(goodsAttribute.getCreateName());
            goodsOptionList.get(i).setAttributeId(attributeId);
            goodsOptionDao.insert(goodsOptionList.get(i));
        }

        return attributeId;
    }

    /**
     * 根据分类id获得规格集
     * @param categoryId
     * @return
     */
    @Override
//    @DataSource(name = DataSourceNames.SECOND)
    public List<GoodsAttributeEntity> getTemplateAttribute(Integer categoryId) {
        List<GoodsAttributeEntity> list = goodsAttributeDao.getTemplateAttribute(categoryId);
        return list;
    }

    /**
     * 标记删除attribute
     * @param longs
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fagDelAttribute(List<Long> longs) {
        goodsAttributeDao.fagDelAttribute(StringUtils.join(longs,","));
    }

    @Override
    public List<GoodsAttributeEntity> selectAttribute(Long goodsId) {
        return goodsAttributeDao.selectAttributes(goodsId);
    }

    @Override
    public List<GoodsAttributeEntity> selectCraft(Long goodsId) {
        return goodsAttributeDao.selectCraft(goodsId);
    }

    @Override
    public List<Map<String,String>> selectListByOptionIds(String optionIds) {
        return goodsAttributeDao.selectListByOptionIds(optionIds);
    }

    @Override
    public List<GoodsAttributeEntity> selectByIds(String attributeIds) {
        return goodsAttributeDao.selectByIds(attributeIds);
    }

    @Override
    public List<GoodsAttributeEntity> getCountAttributeByCategoryId(Integer categoryId) {
        return goodsAttributeDao.getCountAttributeByCategoryId(categoryId);
    }

    @Override
    public Long getCraftAttributeByGoodsId(Long goodsId) {
        return this.baseMapper.getCraftAttributeByGoodsId(goodsId);
    }

    @Override
    public void updateGoodsAttribute(GoodsAttributeEntity goodsAttribute,Long userId) {
        GoodsAttributeEntity oldGoodsAttributeEntity = this.selectById(goodsAttribute.getAttributeId());
        Map<String, Object> map = New.hashMap();
        map.put("attribute_id",goodsAttribute.getAttributeId());
        map.put("disabled",0);
        List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.selectByMap(map);
        oldGoodsAttributeEntity.setGoodsOptionList(goodsOptionEntityList);
        GoodsMonitorEntity goodsMonitorEntity = GoodsMonitorUtils.packingData(oldGoodsAttributeEntity, goodsAttribute, userId);
        if(goodsMonitorEntity.getSdbId() != null){
            goodsMonitorService.insert(goodsMonitorEntity);
        }
        this.updateAllColumnById(goodsAttribute);
    }

    @Override
    public List<Map<String, Object>> getGoodsCraftList() {
        List<Map<String,Object>> goodsCraftList = this.baseMapper.selectGoodsCraftConfig();
        return goodsCraftList;
    }


    /**
     * 定义模板id返回旗下指定类型规格对象
     */
//    @DataSource(name = DataSourceNames.SECOND)
    public List<GoodsAttributeEntity> getAttributeType(Integer templateId,String type){
        List<GoodsAttributeEntity> list = goodsAttributeDao.getAttributeType(templateId,type);
        return list;
    }


}
